<?
/* $Id: connect.php 68 2011-02-23 08:23:14Z jim2212001@gmail.com $ */
require_once 'config.php';
if(!isset($_SESSION['login']) || $_SESSION['provider']=='native')
	exit('不符合連接資格');
if(isset($_GET['action'])){
	$fieldPro = 'id'.$_SESSION['provider'];
	$username = $db->real_escape_string($_POST['username']);
	$nickname = $db->real_escape_string($_POST['nickname']);
 	$res = $db->query('SELECT `password`,`perm` FROM `account` WHERE `username`=\''.$username.'\' LIMIT 1');
	if($row = $res->fetch_assoc()){
		/* Connecting existing account */
		if(SaltMd5::Validate($_POST['password'],$row['password'])){
			$db->query('DELETE FROM `account` WHERE `'.$fieldPro.'` = \''.$_SESSION['login'].'\' LIMIT 1');
			if($db->errno)
			  exit($db->error);
			$db->query('UPDATE `account` SET `name`=\''.$nickname.'\',`'.$fieldPro.'`=\''.$_SESSION['login'].'\',`perm`=perm | '.$row['perm'].' WHERE `username`=\''.$username.'\' LIMIT 1');
			if($db->errno)
			  exit($db->error);
		}else{
			exit('wrong password');
		}
	}else{
		/* Create new account */
		if($_POST['password'] != $_POST['password2']){
			exit('password not match');
		}
		$salt = substr(md5(rand()),0,5);
		$db->query('UPDATE `account` SET `username`=\''.$username.'\', `password`=\''.SaltMd5::Md5($_POST['password'],$salt).'\', `name`=\''.$nickname.'\', `perm`=perm | '.PERM_FOUNDER.
			' WHERE `'.$fieldPro.'`=\''.$_SESSION['login'].'\' LIMIT 1');
		if($db->errno)
		  exit($db->error);
	}
	infoMsg('連結成功，請重新登入');
	redirectMsg('login.php?action=logout');
}
?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<h2>從<?=$_SESSION['provider'];?>連接帳號</h2>
<form action="?action=connect" method="post">
欲連結的帳號 <?=$_SESION['nickname'];?><br />
帳號<input name="username" /><br />
暱稱(請輸入學號)<input name="nickname" value="<?=$_SESSION['nickname'];?>" /><br />
密碼<input name="password" type="password" /><br />
確認密碼*<input name="password2" type="password"><br />
<input type="submit" value="送出**" />
</form>
*創建帳號才需填寫，已有帳號不用填寫
**連接帳號後會自動登出
